// import Cookie from 'js-cookie';

export default {
  //存储数据
  state: {
    token: '',
    // 用户菜单
    menu: []
  },
  //直接更新state的方法，不能写异步代码
  mutations: {
    //从cookie中获取token
    getToken(state) {
      state.token = localStorage.getItem('token');
    },
    //存放token
    setToken(state, val) {
      state.token = val;
      localStorage.setItem('token', val);
    },
    //清空token
    clearToken(state) {
      state.token = '';
      localStorage.removeItem('token');
    },
    //从cookie中获取menu
    getMenu(state) {
      state.menu = JSON.parse(localStorage.getItem('menu'));
    },
    // 清理菜单
    clearMenu(state) {
      //清除也一样 vuex和cookie都清除
      state.menu = [];
      localStorage.removeItem('menu');
    },
    //设置菜单
    setMenu(state, val) {
      //vuex添加
      state.menu = val;
      //cookie也添加
      localStorage.setItem('menu', JSON.stringify(val));
    },
    // 根据菜单添加动态路由
    addMenuRouter(state, router) {
      if (!localStorage.getItem('menu')) {
        return;
      }
      //取出cookie数据 给vuex
      let menu = JSON.parse(localStorage.getItem('menu'));
      state.menu = menu;
      //添加动态路由 主路由为Main.vue
      let currentMenu = [
        {
          path: '/',
          component: () => import(`@/views/Main`),
          children: []
        }
      ];
      //如果是一级菜单 那么菜单名称肯定有路由 如果是二级菜单那么一级没有 二级有路由
      menu.forEach(item => {
        if (item.children) {
          item.children = item.children.map(item => {
            item.component = () => import(`@/views/${item.url}`);
            return item;
          });
          currentMenu[0].children.push(...item.children);
        } else {
          item.component = () => import(`@/views/${item.url}`);
          currentMenu[0].children.push(item);
        }
      });
      //添加动态路由
      router.addRoutes(currentMenu);
    }
  },
  //  commit()来触发mutation的调用 可以包含异步代码(定时器, ajax)
  actions: {},
  getters: {}
};
